// 拼图块的行数和列数
const ROWS = 3;
const COLS = 3;

// 获取拼图容器和打乱按钮
const puzzleContainer = document.getElementById('puzzle-container');
const shuffleButton = document.getElementById('shuffle-button');

// 初始化拼图块数组
let puzzlePieces = [];

// 创建拼图块
function createPuzzlePieces() {
    for (let row = 0; row < ROWS; row++) {
        for (let col = 0; col < COLS; col++) {
            const piece = document.createElement('div');
            piece.classList.add('puzzle-piece');
            piece.style.backgroundPosition = `${-col * 100}px ${-row * 100}px`;
            piece.dataset.row = row;
            piece.dataset.col = col;
            piece.addEventListener('click', handlePieceClick);
            puzzlePieces.push(piece);
            puzzleContainer.appendChild(piece);
        }
    }
}

// 打乱拼图块
function shufflePuzzlePieces() {
    for (let i = puzzlePieces.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [puzzlePieces[i], puzzlePieces[j]] = [puzzlePieces[j], puzzlePieces[i]];
    }
    puzzleContainer.innerHTML = '';
    puzzlePieces.forEach(piece => {
        puzzleContainer.appendChild(piece);
    });
}

// 处理拼图块点击事件
function handlePieceClick() {
    const currentIndex = Array.from(puzzleContainer.children).indexOf(this);
    const emptyIndex = findEmptyPieceIndex();

    const currentRow = parseInt(this.dataset.row);
    const currentCol = parseInt(this.dataset.col);
    const emptyRow = parseInt(puzzlePieces[emptyIndex].dataset.row);
    const emptyCol = parseInt(puzzlePieces[emptyIndex].dataset.col);

    // 检查是否相邻
    if (
        (Math.abs(currentRow - emptyRow) === 1 && currentCol === emptyCol) ||
        (Math.abs(currentCol - emptyCol) === 1 && currentRow === emptyRow)
    ) {
        [puzzlePieces[currentIndex], puzzlePieces[emptyIndex]] = [puzzlePieces[emptyIndex], puzzlePieces[currentIndex]];
        puzzleContainer.innerHTML = '';
        puzzlePieces.forEach(piece => {
            puzzleContainer.appendChild(piece);
        });

        if (isPuzzleSolved()) {
            alert('恭喜你，拼图完成！');
        }
    }
}

// 查找空白拼图块的索引
function findEmptyPieceIndex() {
    // 这里简单假设最后一块为空白块
    return puzzlePieces.length - 1;
}

// 检查拼图是否完成
function isPuzzleSolved() {
    for (let i = 0; i < puzzlePieces.length; i++) {
        const piece = puzzlePieces[i];
        const expectedRow = Math.floor(i / COLS);
        const expectedCol = i % COLS;
        const actualRow = parseInt(piece.dataset.row);
        const actualCol = parseInt(piece.dataset.col);
        if (actualRow!== expectedRow || actualCol!== expectedCol) {
            return false;
        }
    }
    return true;
}

// 初始化游戏
createPuzzlePieces();
shufflePuzzlePieces();

// 打乱按钮点击事件
shuffleButton.addEventListener('click', shufflePuzzlePieces);